package org.doubango.FrCall.network;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.doubango.FrCall.Utils.LogDebugger;
import org.doubango.FrCall.Utils.json.JsonUtils;

/**
 * 网络请求的的线程.
 */
public class Request implements Runnable {

	/**
	 * get
	 */
	public static final String GET = "get";

	/**
	 * post
	 */
	public static final String POST = "post";

	private String uri;

	private String method = GET;

	private List<NameValuePair> formparams = new ArrayList<NameValuePair>();

	/**
	 * constructor.
	 * 
	 * @param uri
	 *            the uri of the request.
	 */
	public Request(String uri) {
		this(uri, GET, null);
	}

	/**
	 * constructor.
	 * 
	 * @param uri
	 *            the uri of the request.
	 * @param method
	 *            "post" or "get"
	 * @param formparams
	 *            NameValuePair list
	 */
	public Request(String uri, String method,
			ArrayList<NameValuePair> formparams) {
		this.uri = uri;
		this.method = method;
		this.formparams = formparams;
	}

	/**
	 * This method will be invoked when request success.
	 * 
	 * @param map
	 *            Map<?, ?>
	 */
	protected void onSuccess(Map<?, ?> map) {

	}

	/**
	 * This method will be invoked when request failure.
	 * 
	 * @param map
	 *            Map<?, ?>
	 */
	protected void onFailure(Map<?, ?> map) {

	}

	@Override
	public void run() {
		String response = null;
		try {
			if (method.equals(GET)) {
				response = HttpConnecter.get(uri);
			} else if (method.equals(POST)) {
				response = HttpConnecter.post(uri, formparams);
			}
		} catch (IOException ioe) {
			LogDebugger.exception(ioe.getMessage());
			onFailure(null);
			return;
		}

		if (response == null) {
			LogDebugger.exception("response data is null.");
			onFailure(null);
			return;
		}

		if (response.startsWith("{") && response.endsWith("}")) {
			Map<?, ?> map;
			map = JsonUtils.bindDataToModel(response);
			String code = (String) map.get("code");
			if (code.startsWith("100")) {
				onSuccess(map);
			} else {
				onFailure(map);
			}
		} else {
			LogDebugger.exception("response data is not json format.");
			onFailure(null);
		}
	}
}
